#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
void getnext(int* next, const char* sub, int len)
{
	next[0] = -1;
	next[1] = 0;
	int i = 2;
	int k = 0;
	while(i<len)
	{
		if (k == -1 || sub[i - 1] == sub[k])
		{
			next[i] = k + 1;
			k++;
			i++;
		}
		else
			k = next[k];
	}
}
int KMP(char* str, char* sub,int pos)
{
	assert(str!=NULL && sub!=NULL);
	int lenstr = strlen(str);
	int lensub = strlen(sub);
	if (lenstr == 0 || lensub == 0)
		return -1;
	if (pos < 0 || pos >= lensub)
		return - 1;
	int i = pos;
	int j = 0;
	int* next = (int*)malloc(sizeof(int) * lensub);
	assert(next != NULL);
	getnext(next, sub, lensub);
	while (i < lenstr && j < lensub)
	{
		if (j==-1||str[i] == sub[j])
		{
			i++;
			j++;
		}
		else
			j = next[j];
	}
	free(next);
	if (j >= lensub)
		return i - j;
	return -1;
}

int main()
{
	printf("%d\n", KMP("ababcabcdabcde", "abcd", 0));
	printf("%d\n", KMP("ababcabcdabcde", "abcdf", 0));
	printf("%d\n", KMP("ababcabcdabcde", "ab", 0));
	return 0;
}